<template>
  <div class="excel-import">
    <el-upload
      class="upload-demo"
      drag
      action="#"
      :http-request="handleUpload"
      :before-upload="beforeUpload"
      :limit="1"
      :file-list="fileList"
      :on-exceed="handleExceed"
      :on-remove="handleRemove"
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将Excel文件拖到此处，或<em>点击上传</em></div>
      <div class="el-upload__tip" slot="tip">只能上传xlsx/xls文件，且不超过10MB</div>
    </el-upload>

    <div v-if="previewData.length > 0" class="preview-section">
      <div class="preview-header">
        <h3>数据预览 (共 {{ previewData.length }} 条)</h3>
        <div class="preview-actions">
          <el-button type="primary" size="small" @click="submitData" :loading="submitting">确认导入</el-button>
          <el-button size="small" @click="cancelImport">取消</el-button>
        </div>
      </div>

      <el-table
          :data="previewData"
          border
          size="mini"
          style="width: 100%"
          max-height="400px"
          v-loading="loading"
      >
        <el-table-column prop="type" label="类型" width="120"></el-table-column>
        <el-table-column prop="category_name" label="分类" width="120"></el-table-column>
        <el-table-column prop="code" label="编码" width="120"></el-table-column>
        <el-table-column prop="name" label="物资设备名称" min-width="150"></el-table-column>
        <el-table-column prop="specification" label="规格型号" width="120"></el-table-column>
        <el-table-column prop="unit" label="计量单位" width="100"></el-table-column>
        <el-table-column prop="quantity" label="数量" width="80"></el-table-column>
        <el-table-column prop="condition" label="技术状况" width="100"></el-table-column>
        <el-table-column prop="status" label="使用状态" width="100"></el-table-column>
        <el-table-column prop="address" label="所在地" width="150"></el-table-column>
        <el-table-column prop="project_name" label="归属单位" width="150"></el-table-column>
        <el-table-column prop="unit_price" label="单位原值" width="100"></el-table-column>
        <el-table-column prop="total_price" label="总原值" width="100"></el-table-column>
        <el-table-column prop="rental_price" label="租售价格" width="100"></el-table-column>
        <el-table-column prop="remark" label="备注" min-width="150"></el-table-column>
        <el-table-column prop="error" label="错误信息" width="200" v-if="hasErrors" fixed="right">
          <template slot-scope="scope">
            <span style="color: #F56C6C">{{ scope.row.error }}</span>
          </template>
        </el-table-column>
      </el-table>
      <el-table
          v-if="errorList.length"
          :data="errorList"
          border
          size="mini"
          style="width: 100%"
          max-height="400px"
          v-loading="loading"
      >
        <el-table-column prop="data.type" label="类型" width="120"></el-table-column>
        <el-table-column prop="data.category_name" label="分类" width="120"></el-table-column>
        <el-table-column prop="data.code" label="编码" width="120"></el-table-column>
        <el-table-column prop="data.name" label="物资设备名称" min-width="150"></el-table-column>
        <el-table-column prop="data.specification" label="规格型号" width="120"></el-table-column>
        <el-table-column prop="data.unit" label="计量单位" width="100"></el-table-column>
        <el-table-column prop="data.quantity" label="数量" width="80"></el-table-column>
        <el-table-column prop="data.condition" label="技术状况" width="100"></el-table-column>
        <el-table-column prop="data.status" label="使用状态" width="100"></el-table-column>
        <el-table-column prop="data.address" label="所在地" width="150"></el-table-column>
        <el-table-column prop="data.project_name" label="归属单位" width="150"></el-table-column>
        <el-table-column prop="data.unit_price" label="单位原值" width="100"></el-table-column>
        <el-table-column prop="data.total_price" label="总原值" width="100"></el-table-column>
        <el-table-column prop="data.rental_price" label="租售价格" width="100"></el-table-column>
        <el-table-column prop="data.remark" label="备注" min-width="150"></el-table-column>
        <el-table-column prop="message" label="错误信息" width="200">
          <template slot-scope="scope">
            <span style="color: #F56C6C">{{ scope.row.message }}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-if="errorList.length > 0" class="preview-section">
      <div class="preview-header">
        <h3>数据预览 (共 {{ uploadRes.total }} 条)</h3>
        <h3>成功 (共 {{ uploadRes.success }} 条)，失败 (共 {{ uploadRes.fail }} 条)</h3>
        <div class="preview-actions">
          <el-button type="primary" size="small" @click="submitData" :loading="submitting">确认导入</el-button>
          <el-button size="small" @click="cancelImport">取消</el-button>
        </div>
      </div>
      <el-table
          v-if="errorList.length"
          :data="errorList"
          border
          size="mini"
          style="width: 100%"
          max-height="400px"
          v-loading="loading"
      >
        <el-table-column prop="data.type" label="类型" width="120"></el-table-column>
        <el-table-column prop="data.category_name" label="分类" width="120"></el-table-column>
        <el-table-column prop="data.code" label="编码" width="120"></el-table-column>
        <el-table-column prop="data.name" label="物资设备名称" min-width="150"></el-table-column>
        <el-table-column prop="data.specification" label="规格型号" width="120"></el-table-column>
        <el-table-column prop="data.unit" label="计量单位" width="100"></el-table-column>
        <el-table-column prop="data.quantity" label="数量" width="80"></el-table-column>
        <el-table-column prop="data.condition" label="技术状况" width="100"></el-table-column>
        <el-table-column prop="data.status" label="使用状态" width="100"></el-table-column>
        <el-table-column prop="data.address" label="所在地" width="150"></el-table-column>
        <el-table-column prop="data.project_name" label="归属单位" width="150"></el-table-column>
        <el-table-column prop="data.unit_price" label="单位原值" width="100"></el-table-column>
        <el-table-column prop="data.total_price" label="总原值" width="100"></el-table-column>
        <el-table-column prop="data.rental_price" label="租售价格" width="100"></el-table-column>
        <el-table-column prop="data.remark" label="备注" min-width="150"></el-table-column>
        <el-table-column prop="message" label="错误信息" width="200" fixed="right">
          <template slot-scope="scope">
            <span style="color: #F56C6C">{{ scope.row.message }}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import * as XLSX from 'xlsx';

export default {
  name: 'ExcelImport',
  props: {
    // 分类数据，用于匹配分类名称到分类ID
    categories: {
      type: Array,
      default: () => []
    },
    // 导入API
    importApi: {
      type: Function,
      required: true
    }
  },
  data() {
    return {
      fileList: [],
      loading: false,
      submitting: false,
      previewData: [],
      previewLimit: 100,
      hasErrors: false,

      // 状态映射
      statusMap: {
        '闲置': 'available',
        '在用': 'reserved'
      },
      errorList: [],
      uploadRes: {
        total: 0,
        success: 0,
        fail: 0
      }
    };
  },
  methods: {
    // 上传前验证
    beforeUpload(file) {
      const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
                      file.type === 'application/vnd.ms-excel';
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isExcel) {
        this.$message.error('上传文件只能是 Excel 格式!');
        return false;
      }
      if (!isLt10M) {
        this.$message.error('上传文件大小不能超过 10MB!');
        return false;
      }

      this.loading = true;
      return true;
    },

    // 处理文件超出限制
    handleExceed() {
      this.$message.warning('只能上传一个文件，请先删除当前文件再上传');
    },

    // 处理文件移除
    handleRemove() {
      this.fileList = [];
      this.previewData = [];
      this.hasErrors = false;
    },

    // 处理上传
    handleUpload(options) {
      const file = options.file;
      this.parseExcel(file);
    },

    // 解析Excel文件
    parseExcel(file) {
      const reader = new FileReader();

      reader.onload = (e) => {
        try {
          const data = new Uint8Array(e.target.result);
          const workbook = XLSX.read(data, { type: 'array' });

          // 获取第一个工作表
          const firstSheetName = workbook.SheetNames[0];
          const worksheet = workbook.Sheets[firstSheetName];

          // 转换为JSON
          const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

          // 处理数据
          this.processData(jsonData);
        } catch (error) {
          this.$message.error('解析Excel文件失败: ' + error.message);
          this.loading = false;
        }
      };

      reader.onerror = () => {
        this.$message.error('读取文件失败');
        this.loading = false;
      };

      reader.readAsArrayBuffer(file);
    },

    // 处理Excel数据
    processData(data) {
      if (!data || data.length < 2) {
        this.$message.error('Excel文件格式不正确或没有数据');
        this.loading = false;
        return;
      }

      // 获取表头
      const headers = data[0];
      const expectedHeaders = ['类型', '分类', '编码', '物资设备名称', '规格型号', '计量单位', '数量', '技术状况', '使用状态', '所在地', '归属单位', '单位原值', '租售价格', '备注'];

      // 验证表头
      const missingHeaders = expectedHeaders.filter(header => !headers.includes(header));
      if (missingHeaders.length > 0) {
        this.$message.error(`Excel文件缺少必要的列: ${missingHeaders.join(', ')}`);
        this.loading = false;
        return;
      }

      // 处理数据行
      const processedData = [];
      let hasErrors = false;

      for (let i = 1; i < data.length; i++) {
        const row = data[i];
        if (row.length === 0 || !row.some(cell => cell)) continue; // 跳过空行

        const item = {};
        let error = null;

        // 映射数据
        for (let j = 0; j < headers.length; j++) {
          const header = headers[j];
          const value = row[j];

          switch (header) {
            case '类型':
              item.type = value;
              // 查找分类ID
              // const category = this.findCategory(value);
              // if (category) {
              //   item.category_id = category.id;
              //   item.type = category.type;
              // } else {
              //   error = '找不到匹配的分类';
              // }
              break;
            case '分类':
              // 查找分类ID
              const category = this.findCategory(value);
              if (category) {
                item.category_id = category.id;
                item.category_name = category.name;
              } else {
                error = '找不到匹配的分类';
              }
            case '物资设备名称':
              item.name = value;
              if (!value) {
                error = '物资设备名称不能为空';
              }
              break;
            case '编码':
              item.code = value;
              break;
            case '规格型号':
              item.specification = value;
              break;
            case '计量单位':
              item.unit = value;
              if (!value) {
                error = '计量单位不能为空';
              }
              break;
            case '数量':
              item.quantity = parseFloat(value) || 0;
              if (isNaN(item.quantity)) {
                error = '数量必须为数字';
              }
              break;
            case '技术状况':
              item.condition = value
              break;
            case '使用状态':
              if (value === '闲置') {
                item.status = 'available';
              } else {
                item.status = 'reserved';
              }
              break;
            case '所在地':
              item.address = value;
              // 尝试解析省市
              let list = value.split('/')
              if (list.length >= 2) {
                item.province = list[0]
                item.city = list[1]
              }
              break;
            case '归属单位':
              item.project_name = value;
              break;
            case '单位原值':
              item.unit_price = value
              break;
            case '租售价格':
              item.rental_price = value
              break;
            case '折扣率':
              item.discount_rate = value || 100
              break;
            case '备注':
              item.remark = value;
              break;
          }

          item.total_price = item.unit_price * item.quantity
        }

        if (error) {
          item.error = error;
          hasErrors = true;
        }

        processedData.push(item);
      }

      this.previewData = processedData;
      this.hasErrors = hasErrors;
      this.loading = false;

      if (hasErrors) {
        this.$message.warning('导入数据存在错误，请检查后再提交');
      } else if (processedData.length === 0) {
        this.$message.warning('没有找到有效数据');
      } else {
        this.$message.success(`成功解析 ${processedData.length} 条数据，请确认后提交`);
      }
    },

    // 查找分类
    findCategory(categoryName) {
      if (!categoryName) return null;

      // 递归查找分类
      const findInCategories = (categories) => {
        for (const category of categories) {
          if (category.name === categoryName) {
            return category;
          }
          if (category.children && category.children.length > 0) {
            const found = findInCategories(category.children);
            if (found) return found;
          }
        }
        return null;
      };

      return findInCategories(this.categories);
    },

    // 提交数据
    submitData() {
      if (this.hasErrors) {
        this.$confirm('数据中存在错误，确定要继续导入吗？', '警告', {
          confirmButtonText: '继续导入',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.doSubmit();
        }).catch(() => {});
      } else {
        this.doSubmit();
      }
    },

    // 执行提交
    doSubmit() {
      if (this.previewData.length === 0) {
        this.$message.warning('没有数据可导入');
        return;
      }

      this.submitting = true;

      // 过滤掉有错误的数据
      const validData = this.previewData.filter(item => !item.error);
      console.log('validData',validData)
      // 调用导入API
      this.importApi(validData).then(res => {
        this.$message.success(`导入成功，共${res.data.total}条，成功${res.data.success}条，失败${res.data.fail}条`);
        if (res.data.fail) {
          this.errorList = res.data.errors
          this.fileList = [];
          this.previewData = [];
          this.hasErrors = false;
          this.uploadRes = res.data
        } else {
          this.cancelImport();
          this.$emit('import-success');
        }
        this.submitting = false;
      }).catch(error => {
        this.$message.error(error.message || '导入失败');
        this.submitting = false;
      });
    },

    // 取消导入
    cancelImport() {
      this.fileList = [];
      this.previewData = [];
      this.hasErrors = false;
      this.$emit('cancel');
    }
  }
};
</script>

<style scoped>
.excel-import {
  width: 100%;
}
.preview-section {
  margin-top: 20px;
}
.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}
.preview-actions {
  display: flex;
  gap: 10px;
}
.preview-more {
  margin-top: 15px;
}
</style>
